package com.dubbo.provider.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.dubbo.ITransferAPI;
import com.dubbo.provider.dao.db1.ITransferDaoA;
import com.dubbo.provider.dao.db2.ITransferDaoB;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

@Component
@Service(interfaceClass = ITransferAPI.class, timeout = 10000)
public class TransferService implements ITransferAPI {

    @Autowired
    private ITransferDaoA iTransferDaoA;

    @Autowired
    private ITransferDaoB iTransferDaoB;

    @Transactional
    @Override
    public boolean doTransfer(String from, String to, Integer sum) {

        /**
         * 这是一次事务，
         */
        for (int i = 0; i < 10; i++) {
            // 先从from处减金额
            iTransferDaoA.decreaseABalance(sum);

            // 再给to加相同的金额
            iTransferDaoB.increaseBBalance(sum);
            try {
                System.out.println("==========第" + i + "次转账=======");
//                Thread.sleep(3000);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }


        // 然后看一下from的余额是否为负数
        Integer balance = iTransferDaoA.getABalance();
        if (balance < 0) {
            throw new RuntimeException("余额不足，回滚！");
        } else {
            return true;
        }
    }
}
